package com.aaa.controller;

import com.aaa.config.JwtToken;
import com.aaa.entity.R;
import com.aaa.entity.WxUser;
import com.aaa.mapper.WxUserMapper;
import com.aaa.utils.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;

/**
 * 微信小程序接口
 */
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxLoginController {

    @Resource
    private WxUserMapper wxUserMapper;

    /**
     * 小程序登录
     */
    @PostMapping("/login")
    public R login(Model model, HttpServletRequest request, @RequestBody WxUser wxUser) {
        String openid = WxUtil.getOpenid(wxUser.getCode());
        if (openid == null) {
            return R.error().message("获取openid失败");
        }

        WxUser user = wxUserMapper.queryByOpenId(openid);
        if (user == null) {
            user = new WxUser();
            user.setOpenId(openid);
            user.setHeadImg(wxUser.getHeadImg());
            user.setIdCard(wxUser.getIdCard());
            user.setNickname(wxUser.getNickname());
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());

            wxUserMapper.add(user);
        }else {
            user.setOpenId(openid);
            user.setHeadImg(wxUser.getHeadImg());
            user.setIdCard(wxUser.getIdCard());
            user.setNickname(wxUser.getNickname());
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            wxUserMapper.edit(user);
        }

        //第一步：建立subject
        Subject subject = SecurityUtils.getSubject();
        //第二步：封装token  凭证
        JwtToken token = new JwtToken(openid, "123456","wechat");
        //第三步：登陆
        String id = subject.getSession().getId().toString();
        user.setSessionId(id);
        try {
            //只要能通过认证就能通过了
            subject.login(token);

            //把user放进session
            request.getSession().setAttribute("user", user);
            model.addAttribute("loginname", user.getNickname());
            model.addAttribute("id", user.getId());
            //把yonghu放进session
            request.getSession().setAttribute("yonghu", user.getNickname());
            return R.ok().entity(user);
        } catch (UnknownAccountException e) {
            //用户为空或不存在
            return R.error().message("不存在这样的用户!");
        }
    }


}
